package org.redis.cluster.logback;

import java.io.File;
import java.net.URL;

import org.redis.cluster.Constants;
import org.redis.cluster.RedisCluster;
import org.redis.cluster.plugin.AbstractPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.StaticLoggerBinder;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;

public class LogbackPlugin extends AbstractPlugin {
	
	private final static String FILE="logger.xml";
	
	private final static String FILE_PATH="/conf/logger.xml";
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());

	@Override
	public void init(RedisCluster redisCluster) {
		String homePath=System.getProperty(Constants.HOME_PATH);
		String logFilePath=homePath+FILE_PATH;
		File logFile=new File(logFilePath);
		if(!logFile.exists()) {
			URL logFileUrl=LogbackPlugin.class.getClassLoader().getResource(FILE);
			
			if(logFileUrl==null) {
				if(logger.isWarnEnabled()) {
					logger.warn("找不到日志文件 - {}",logFilePath);
				}
				
				return;
			}
			
			logFilePath=logFileUrl.getPath();
		}
		
		LoggerContext loggerContext=(LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory();
		loggerContext.reset();
		JoranConfigurator configurator=new JoranConfigurator();
        configurator.setContext(loggerContext);
        
        try {
        	configurator.doConfigure(logFilePath);
        }
        catch(Exception e) {
        	throw new RuntimeException(e);
        }
        
        if(logger.isInfoEnabled()) {
        	logger.info("使用日志  - {}",logFilePath);
        }
	}
}